<template>
  <div class="tree-main-body">
    <!-- 左侧部门树 -->
    <div class="left-box">
      <TreeDepartment
        :selected="depIds"
        :refresh="refresh"
        :showNum="true"
        text="部门"
        @update="handleDepartmentUpdate"
      />
    </div>

    <!-- 右侧 -->
    <div class="right-box">
      <div class="playedu-main-title float-left mb-24">
        学员 | {{ selLabel }}
      </div>

      <!-- 顶部按钮和搜索框 -->
      <div class="float-left j-b-flex mb-24">
        <div class="d-flex">
          <PerButton
            v-if="!ldapEnabled"
            type="primary"
            text="添加学员"
            class="mr-16"
            :icon="h(PlusOutlined)"
            p="user-store"
            @click="createVisible = true"
          />
          <RouterLink
            v-if="!ldapEnabled && depIds.length === 0"
            style="text-decoration: none"
            to="/member/import"
          >
            <PerButton
              type="default"
              text="批量导入学员"
              class="mr-16"
              p="user-store"
            />
          </RouterLink>
        </div>

        <!-- 搜索条件 -->
        <div class="d-flex">
          <div class="d-flex mr-24">
            <Typography.Text>姓名：</Typography.Text>
            <a-input
              v-model:value="nickname"
              style="width: 160px"
              placeholder="请输入姓名关键字"
              allowClear
            />
          </div>
          <div class="d-flex mr-24">
            <Typography.Text>邮箱：</Typography.Text>
            <a-input
              v-model:value="email"
              style="width: 160px"
              placeholder="请输入邮箱账号"
              allowClear
            />
          </div>
          <div class="d-flex">
            <a-button class="mr-16" @click="resetData">重置</a-button>
            <a-button type="primary" @click="queryData">查询</a-button>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :dataSource="list"
        :loading="loading"
        :pagination="paginationProps"
        rowKey="id"
      />

      <!-- 弹窗：新建学员 -->
      <MemberCreate
        :open="createVisible"
        :depIds="depIds"
        @cancel="() => { createVisible = false; toggleRefresh(); }"
      />
      <!-- 弹窗：编辑学员 -->
      <MemberUpdate
        :id="mid"
        :open="updateVisible"
        @cancel="() => { updateVisible = false; toggleRefresh(); }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h, onMounted, computed } from "vue";
import { useRoute, useRouter, RouterLink } from "vue-router";
import {
  Typography,
  Input as AInput,
  Button as AButton,
  Table as ATable,
  Modal,
  message,
  Image,
  Dropdown,
  Space,
} from "ant-design-vue";
import {
  PlusOutlined,
  DownOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons-vue";
import { user } from "../../api";
import { dateFormat } from "../../utils";
import TreeDepartment from "@/components/Common/tree-department.vue";
import PerButton from "@/components/Common/permission-button.vue";
import MemberCreate from "./create.vue";
import MemberUpdate from "./upload.vue";
import memberDefaultAvatar from "@/assets/thumb/avatar.png";

// import MemberUpdate from "@/components/Common/test111.vue";


const route = useRoute();
const router = useRouter();

const page = ref(Number(route.query.page) || 1);
const size = ref(Number(route.query.size) || 10);
const nickname = ref(route.query.nickname as string || "");
const email = ref(route.query.email as string || "");

const loading = ref(false);
const list = ref<any[]>([]);
const resourceUrl = ref<Record<string, string>>({});
const total = ref(0);
const refresh = ref(false);
const depIds = ref<number[]>([]);
const selLabel = ref((route.query.label as string) || "全部部门");
const createVisible = ref(false);
const updateVisible = ref(false);
const mid = ref(0);
const userDepIds = ref<Record<number, number[]>>({});
const departments = ref<Record<number, string>>({});

// LDAP 开关
const ldapEnabled = computed(() => false); // 这里先写死，实际用 store.state.systemConfig.value["ldap-enabled"]

// 刷新列表
function toggleRefresh() {
  refresh.value = !refresh.value;
}

// 获取数据
async function getData() {
  if (loading.value) return;
  loading.value = true;
  try {
    const res: any = await user.userList(page.value, size.value, {
      name: nickname.value,
      email: email.value,
      dep_ids: depIds.value.join(","),
    });
    list.value = res.data.data;
    departments.value = res.data.departments;
    userDepIds.value = res.data.user_dep_ids;
    resourceUrl.value = res.data.resource_url;
    total.value = res.data.total;
  } finally {
    loading.value = false;
  }
}

watch([refresh, page, size, depIds], getData, { immediate: true });

// 表格列
const columns = [
  {
    title: "学员",
    dataIndex: "name",
    width: 300,
    customRender: ({ record }: any) => {
      return h("div", { class: "d-flex" }, [
        h(Image, {
          src: record.avatar == -1 ? memberDefaultAvatar : resourceUrl.value[record.avatar],
          preview: false,
          width: 40,
          height: 40,
          style: { borderRadius: "50%" },
        }),
        h("span", { style: { marginLeft: "8px" } }, record.name),
      ]);
    },
  },
  {
    title: "所属部门",
    dataIndex: "id",
    customRender: ({ record }: any) => {
      const id = record.id;
      if (!userDepIds.value[id]) return "";
      return userDepIds.value[id].map((item: number, index: number) => {
        return index === userDepIds.value[id].length - 1
          ? departments.value[item]
          : departments.value[item] + "、";
      });
    },
  },
  {
    title: "登录邮箱",
    dataIndex: "email",
  },
  {
    title: "加入时间",
    dataIndex: "created_at",
    customRender: ({ text }: any) => dateFormat(text),
  },
    {
    title: "操作",
    key: "action",
    width: 160,
    customRender: ({ record }: any) => {
        return h(Space, { size: "small" }, [
        // 学习按钮
        h(
            RouterLink,
            { to: `/member/learn?id=${record.id}&name=${record.name}` },
            {
            default: () =>
                h(PerButton, {
                type: "link",
                text: "学习",
                class: "b-link c-red",
                p: "user-learn",
                }),
            }
        ),
        // 更多下拉菜单
        !ldapEnabled.value &&
            h(Dropdown, 
            {
                trigger: ["click"],
                placement: "bottomRight",
            },
            {
                default: () =>
                h(
                    AButton,
                    { type: "link", class: "b-link c-red" },
                    { default: () => ["更多", h(DownOutlined)] }
                ),
                overlay: () =>
                h(
                    "div",
                    { class: "dropdown-menu" },
                    [
                    h(PerButton, {
                        type: "link",
                        text: "编辑",
                        class: "b-link c-red",
                        p: "user-update",
                        onClick: () => {
                        mid.value = record.id;
                        updateVisible.value = true;
                        },
                    }),
                    h(PerButton, {
                        type: "link",
                        text: "删除",
                        class: "b-link c-red",
                        p: "user-destroy",
                        onClick: () => delUser(record.id),
                    }),
                    ]
                ),
            }
            ),
        ]);
    },
    },

];

// 分页配置
const paginationProps = reactive({
  current: page,
  pageSize: size,
  total,
  showSizeChanger: true,
  onChange: (p: number, ps: number) => {
    page.value = p;
    size.value = ps;
  },
});

// 删除用户
function delUser(id: number) {
  if (id === 0) return;
  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "确认删除此学员？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    async onOk() {
      await user.destroyUser(id);
      message.success("操作成功");
      toggleRefresh();
    },
  });
}

// 部门树选择
function handleDepartmentUpdate(keys: number[], title: string) {
  page.value = 1;
  depIds.value = keys;
  const index = title.indexOf("(");
  selLabel.value = index !== -1 ? title.substring(0, index) : title;
}

// 搜索重置
function resetData() {
  page.value = 1;
  size.value = 10;
  nickname.value = "";
  email.value = "";
  list.value = [];
  toggleRefresh();
}

// 查询
function queryData() {
  page.value = 1;
  toggleRefresh();
}
</script>
<style scoped>

</style>